package com.ytjj.qmyx.mall.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.request.AliyunMallPVRequest;
import com.ytjj.common.model.request.AliyunMallRequest;
import com.ytjj.common.utils.*;
import com.ytjj.qmyx.mall.constants.PayModeConstant;
import com.ytjj.qmyx.mall.enums.ProductStatusEnums;
import com.ytjj.qmyx.mall.mapper.OrdersSpecMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.H5CreateOrderRequest;
import com.ytjj.qmyx.mall.model.response.ProductSpecResponse;
import com.ytjj.qmyx.mall.service.*;
import com.ytjj.qmyx.users.client.UsersClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * H5 普通商品订单
 *
 *
 * @version 1.0
 *
 */
@Service("H5NORMAL")
@Slf4j
@RefreshScope
public class H5OrdersNormalServiceImpl implements CreateOrderService<H5CreateOrderRequest> {

    @Autowired
    private UsersClient usersClient;

    @Autowired
    private ProductService productService;

    @Autowired
    private SysConfigUtil sysConfigUtil;

    @Autowired
    private OrdersService ordersService;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private OrdersSpecMapper ordersSpecMapper;
    @Value("${h5Order.subAmount:20}")
    private String maxSubAmount;
    @Value("${check.product.status:1}")
    private String checkProductStatus;//是否校验商品状态 1-校验  0-不需要校验

    // 创建一个固定大小的线程池，可以根据需要调整线程池的大小
    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    public Integer createOrder(H5CreateOrderRequest request) {
        Integer userId = null;
        if(StringUtils.isNotEmpty(request.getTel())){
            // 获取用户id 用户服务处理
            userId = usersClient.h5GetUserIdByTel(request.getTel(), request.getChannel(), TokenUtil.getToken());
        }
        // 普通商品创建订单
        ProductSpec productSpec = productService.getProductSpecById(request.getProductSpecId());
        Product product = productMapper.selectByPrimaryKey(productSpec.getProductId());
        Optional.ofNullable(product)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));
        if (checkProductStatus.equals("1")) {
            if (ProductStatusEnums.UP.getValue() != product.getStatus()) {
                throw new ApiException("商品已下架");
            }
        }
        Integer isDirectBuy = 0;
        // 支付方式为 “直接购买” 则取出现价字段
        if(PayModeConstant.ORIGINAL_PRICE.equals(request.getFlag())){
            productSpec.setPrice(productSpec.getCurPrice());
            isDirectBuy = 1;
        }
        if (null == request.getSubAmount()) {
            request.setSubAmount(0);
        }
        if (request.getSubAmount() > Integer.parseInt(maxSubAmount)) {
            request.setSubAmount(Integer.parseInt(maxSubAmount));
        }
        String orderParentNo = OrderUtils.getOrderCode(userId);//组合订单号
        BigDecimal price = productSpec.getPrice();
//        try {
//            log.info("===h5 create order sub amount={}", request.getSubAmount());
//            price = price.subtract(new BigDecimal(String.valueOf(request.getSubAmount())));
//            log.info("===calcution amount ={}", price);
//        } catch (Exception e) {
//            log.error("===h5 create order sub amount is err==={}, {}", orderParentNo, request.getSubAmount());
//            log.info("==={}", e);
//        }
        //乘商品数量
        BigDecimal originalPrice_new = productSpec.getOriginalPrice();
        BigDecimal price_new = price;
        if (null != request.getProductSum() && request.getProductSum() > 1){
            originalPrice_new = productSpec.getOriginalPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
            price_new = price.multiply(BigDecimal.valueOf(request.getProductSum()));
        }
        //使用优惠卷
        BigDecimal couponNum =null;
        if (request.getCoupon()!=null && request.getCoupon().equals(1) && product.getOriginalPrice()!=null && product.getPrice()!=null){
            couponNum = product.getOriginalPrice().subtract(product.getPrice());
            if (couponNum.compareTo(BigDecimal.ZERO) > 0 && (price_new.subtract(couponNum)).compareTo(BigDecimal.ZERO) > 0){
                price_new = price_new.subtract(couponNum);
            }
        }
        // 主订单
        Orders orders = ordersService.saveOrders(userId, request.getTel(),request.getProvince(),request.getCity(),request.getArea(), request.getAddress(), request.getUserName(),
                originalPrice_new, price_new,
                request.getOrderSource(),request.getChannel(),TokenUtil.getToken(),orderParentNo,request.getDomainUrl(),request.getOrderPlatform(),couponNum);
        // 明细订单
        OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
                productSpec.getPrice(), productSpec.getOriginalPrice(), product.getWarehouse(), product.getWarehouseName(),
                product.getWarehouseRule(), request.getSpecialId(), productSpec.getSkuSpec(), product.getBankerId(), productSpec.getId(),
                product.getActivityType(), null, product.getActivityMax(), product.getActivityMin(), product.getDescr(),isDirectBuy,request.getPageSourceV2(),
                null,product.getProductType(),0, productSpec.getCostPrice(), productSpec.getThreeSkuId(),request.getProductSum(),"",request.getScene());

        try {
            //记录订单规格信息
            ProductSpec productSpecs = ordersSpecMapper.selectOrderSpec(request.getProductSpecId());
            ordersSpecMapper.insertOrderSpec(productSpecs.getSkuSpec(),orders.getId(),productSpecs.getPrice(),productSpecs.getOriginalPrice(),productSpecs.getCostPrice());
        }catch (Exception e){
            log.error("记录订单规格信息错误",e);
        }
        AliyunMallRequest aliyunMallRequest = new AliyunMallRequest();
        AliyunMallPVRequest aliyunMallPVRequestRequest = new AliyunMallPVRequest();

        try {
            //阿里云订单数据
            String batchName = TokenUtil.getRequest().getHeader("batchName");
            aliyunMallRequest.setBatchName(batchName);
            aliyunMallRequest.setChannelCode(request.getChannel());
            aliyunMallRequest.setOrderTime(DateTimeUtil.TimeToStr(orders.getCreateTime()));
            aliyunMallRequest.setProvince(request.getProvince());
            aliyunMallRequest.setStatus("1");
            aliyunMallRequest.setOrderNo(ordersInfo.getChildOrderNo());
            aliyunMallRequest.setPhone(request.getTel());
            aliyunMallRequest.setPaymentAmount(orders.getRealTotalMoney().toString());
            aliyunMallRequest.setName(request.getUserName());
            aliyunMallRequest.setCost(ordersInfo.getCostPrice().toString());


            //阿里云埋点你数据
            aliyunMallPVRequestRequest.setBatchName(batchName);
            aliyunMallPVRequestRequest.setChannelCode(request.getChannel());
            aliyunMallPVRequestRequest.setCreateTime(DateTimeUtil.getTime());
            aliyunMallPVRequestRequest.setOperationNode("3");
            aliyunMallPVRequestRequest.setToken(TokenUtil.getToken());
        } catch (Exception e) {
            log.error("组装数据报错,{}",e);
        }

        // 推送订单数据到阿里云
        executorService.submit(() -> {
            try {
                if(StringUtils.isNotBlank(aliyunMallRequest.getPhone())){
                    AliyunMallApiUtil.orderPush(aliyunMallRequest);
                }
            } catch (Exception e) {
                log.error("创建订单推送阿里云失败", e);
            }

            try {
                log.info("aliyunMallPVRequestRequest,{}", JSON.toJSONString(aliyunMallPVRequestRequest));
                AliyunMallApiUtil.pvPush(aliyunMallPVRequestRequest);
            } catch (Exception e) {
                log.error("埋点数据推送阿里云失败", e);
            }
        });


        return orders.getId();
    }


    // 在销毁服务时关闭线程池
    @PreDestroy
    public void shutdown() {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
    }

    @Override
    public Integer cartCreateOrder(H5CreateOrderRequest request) {
        return null;
    }
}
